package com.example.springbootdemo.es7;

import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

public class ElasticsearchOfIndex {
    // 创建索引
    public static final ElasticsearchTask createIndex = client -> {
        try {
            CreateIndexRequest request = new CreateIndexRequest("user");
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
            System.out.println("Create index response: " + response.isAcknowledged());
        } catch (Exception e) {
            if (e instanceof ElasticsearchStatusException) {
                System.out.println("Create Index`s already exists");
            } else {
                e.printStackTrace();
            }
        }
    };
    // 查询索引
    public static final ElasticsearchTask searchIndex = client -> {
        GetIndexRequest request = new GetIndexRequest("user");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        System.out.println("Search Response: " + response.toString());
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println("Exists: " + exists);
    };
    // 删除索引
    public static final ElasticsearchTask deleteIndex = client -> {
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println("Delete Response: " + response.isAcknowledged());
    };
    // 主程序
    public static void main(String[] args) {
//        ConnectElasticsearch.connect(createIndex, searchIndex, deleteIndex);
        ConnectElasticsearch.connect(createIndex, searchIndex);
    }
}
